package com.forward.uploadapp.adapter;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.forward.uploadapp.R;
import com.forward.uploadapp.entity.AppInfo;
import com.forward.uploadapp.util.ToolUtils;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * Created by ljh on 17-12-18.
 */

public class GetJsonAdapter extends BasicAdapter {
    private List<AppInfo> mDatas;
    private StringBuffer mBuffer;

    public GetJsonAdapter(Context context, List<AppInfo> data) {
        super(context);
        mDatas = data;
        mBuffer = new StringBuffer();
    }

    @Override
    public int getCount() {
        return mDatas == null ? 0 : mDatas.size();
    }

    @Override
    public Object getItem(int position) {
        return mDatas == null ? null : mDatas.get(position);
    }

    @Override
    public long getItemId(int position) {
        return mDatas != null ? mDatas.get(position).getTaskId() : 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            convertView = LayoutInflater.from(mContext).inflate(R.layout.text, parent, false);
            holder = new ViewHolder(convertView);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        AppInfo appInfo = mDatas.get(position);
        holder.text.setText(getShowStr(appInfo));
        return convertView;
    }

    private String getShowStr(AppInfo appInfo) {
        if (appInfo == null) {
            return "";
        }
        mBuffer.delete(0, mBuffer.length());
        mBuffer.append(appInfo.getTaskId()).append("  ");
        mBuffer.append(appInfo.getAppName()).append("  ");
        mBuffer.append(appInfo.getPackageName()).append("  ");
        return mBuffer.toString();
    }

    public void refresh() {
        Collections.sort(mDatas, new Comparator<AppInfo>() {
            @Override
            public int compare(AppInfo o1, AppInfo o2) {
                return o1.getTaskId() < o2.getTaskId() ? 1 : -1;
            }
        });
        notifyDataSetChanged();
    }

    private class ViewHolder {
        private TextView text;

        public ViewHolder(View view) {
            text = (TextView) view.findViewById(R.id.text);
        }
    }
}
